package edu.levantai;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class AddEditCountry extends Activity {
	private long rowID;
	private EditText nameEt;
	private EditText capEt;
	private EditText codeEt;

	protected TextView title;
	protected ImageView icon;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

		setContentView(R.layout.add_country);

		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.window_title);

		title = (TextView) findViewById(R.id.lblTitle);
		icon = (ImageView) findViewById(R.id.imgIcon);

		this.title.setText(R.string.lblAddTitle);
		this.icon.setImageResource(R.drawable.icon_add);

		nameEt = (EditText) findViewById(R.id.nameEdit);
		capEt = (EditText) findViewById(R.id.capEdit);
		codeEt = (EditText) findViewById(R.id.codeEdit);

		Bundle extra = getIntent().getExtras();
		if (extra != null) {
			rowID = extra.getLong("row_id");
			nameEt.setText(extra.getString("name"));
			capEt.setText(extra.getString("cap"));
			codeEt.setText(extra.getString("code"));
		}

		Button saveButton = (Button) findViewById(R.id.btnSave);
		saveButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (nameEt.getText().length() != 0) {
					AsyncTask<Object, Object, Object> saveContactTask = new AsyncTask<Object, Object, Object>() {

						@Override
						protected Object doInBackground(Object... params) {
							saveContact();
							return null;
						}

						@Override
						protected void onPostExecute(Object result) {
							finish();
						}

					};
					saveContactTask.execute((Object[]) null);
				}

			}

		});

	}

	private void saveContact() {
		DatabaseConnector dbConnector = new DatabaseConnector(this);

		if (getIntent().getExtras() == null) {
			dbConnector.insertContact(nameEt.getText().toString(), capEt
					.getText().toString(), codeEt.getText().toString());

		} else {
			dbConnector.updateContact(rowID, nameEt.getText().toString(), capEt
					.getText().toString(), codeEt.getText().toString());
		}

	}

}
